package com.tbit.uqbike.service.business.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tbit.uqbike.constant.UserConstant;
import com.tbit.uqbike.manager.exception.BaseException;
import com.tbit.uqbike.object.pojo.RideFeeLog;
import com.tbit.uqbike.object.pojo.SubAccount;
import com.tbit.uqbike.object.pojo.dto.RideFeeLogDownloadDTO;
import com.tbit.uqbike.object.pojo.dto.RideFeeLogStatisticsDTO;
import com.tbit.uqbike.object.pojo.vo.*;
import com.tbit.uqbike.object.value.LoginInfo;
import com.tbit.common.entity.view.PageResult;
import com.tbit.uqbike.service.base.TokenService;
import com.tbit.uqbike.service.business.SubAccountLogService;
import com.tbit.uqbike.webmanager.dao.capital.AdaPayCapitalDao;
import com.tbit.uqbike.webmanager.dao.capital.RideFeeLogDao;
import com.tbit.uqbike.webmanager.dao.core.AccountDao;
import com.tbit.uqbike.webmanager.dao.core.RechargeDao;
import com.tbit.uqbike.webmanager.dao.core.SubAccountDao;
import com.tbit.uqbike.webmanager.dao.log.SubAccountLogDao;
import com.tbit.uqbike.webmanager.dao.stat.AccountDayStatDao;
import com.tbit.uqbike.webmanager.dao.stat.AccountSumStatDao;
import com.tbit.uqbike.webmanager.dao.stat.LedgerManagementDao;
import com.tbit.uqbike.webmanager.util.StringUtils;
import com.tbit.uqbike.webmanager.util.csv.CsvExportUtils;
import com.tbit.uqbike.webmanager.util.csv.entity.ExportHandler;
import com.tbit.utils.Assert;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;
import java.util.function.IntSupplier;
import java.util.stream.Collectors;

/**
 * 分账日志接口实现类
 *
 * @Author:BUGTian
 * @DATE: 2022/5/26
 */
@Service
public class SubAccountLogServiceImpl implements SubAccountLogService {
    @Autowired
    private SubAccountLogDao subAccountLogDao;

    @Autowired
    private SubAccountDao subAccountDao;

    @Autowired
    private AccountDao accountDao;
    @Resource
    private RideFeeLogDao rideFeeLogDao;
    @Resource
    private AdaPayCapitalDao adaPayCapitalDao;
    @Autowired
    private CsvExportUtils csvExportUtils;
    @Autowired
    private RechargeDao rechargeDao;
    @Autowired
    private LedgerManagementDao ledgerManagementDao;
    @Autowired
    private TokenService tokenService;
    @Resource
    private AccountSumStatDao accountSumStatDao;
    @Resource
    private AccountDayStatDao accountDayStatDao;

    @Override
    public PageResult<SubAccountLogVO> querySubAccountLogPage(LoginInfo loginInfo, Integer page, Integer size, Date startTime, Date endTime, Integer accountId, Integer adAccountId, String userNO, String buyOrderNO,String confirmId,String type) {
        String checkUserNo = check(loginInfo, userNO);
        PageInfo<SubAccountLogVO> pageInfo = PageHelper.startPage(page, size).doSelectPageInfo(() -> adaPayCapitalDao.querySubAccountLogPage(startTime, endTime, accountId, adAccountId, checkUserNo, buyOrderNO,confirmId,type));
        return new PageResult<>(page, size, pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getList());

    }

    @Override
    public PageResult<SubAccountLogOverviewVO> querySubAccountLogOverviewPage(LoginInfo loginInfo, Integer page, Integer size, Date startTime, Date endTime, Integer accountId, Integer adAccountId, String userNO) {
        String checkUserNo = check(loginInfo, userNO);
        //预统计表拿数据
        PageInfo<SubAccountLogOverviewVO> pageInfo = PageHelper.startPage(page, size).doSelectPageInfo(() -> adaPayCapitalDao.querySubAccountLogOverviewPageOnce(startTime, endTime, accountId, adAccountId, checkUserNo));
        return new PageResult<>(page, size, pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getList());
    }


    @Override
    public PageResult<SubAccountLogOverviewVO> querySubAccountLogOverviewPageByDay(LoginInfo loginInfo, Integer page, Integer size, Date startTime, Date endTime, Integer accountId, Integer adAccountId, String userNO) {
        String checkUserNo = check(loginInfo, userNO);
        PageInfo<SubAccountLogOverviewVO> pageInfo = PageHelper.startPage(page, size).doSelectPageInfo(() -> adaPayCapitalDao.querySubAccountLogOverviewPageOnceByDay(startTime, endTime, accountId, adAccountId, checkUserNo));
        return new PageResult<>(page, size, pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getList());
    }

    @Override
    public PageResult<SubAccountUserRefundVO> querySubAccountUserRefund(LoginInfo loginInfo, Integer page, Integer size, Date startTime, Date endTime, Integer accountId, Integer adAccountId, String userNO, String buyOrderNO,String confirmId,String type) {
        String checkUserNo = check(loginInfo, userNO);
        Map<String, String> subAccountNames = subAccountDao.selectByAccountId(accountId)
                .stream().collect(Collectors.toMap(SubAccount::getMemberId, SubAccount::getNickName, (v1, v2) -> v2));
        //查询退款明细
        PageInfo<SubAccountUserRefundVO> pageInfo = PageHelper.startPage(page, size).doSelectPageInfo(() -> adaPayCapitalDao.querySubAccountUserRefund(startTime, endTime, accountId, adAccountId, checkUserNo, buyOrderNO, confirmId,type));
        // 补充信息
        pageInfo.getList().forEach(subAccountUserRefund -> subAccountUserRefund.setNickName(subAccountNames.get(subAccountUserRefund.getUserNO())));
        return new PageResult<>(page, size, pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getList());
    }

    @Override
    public List<SubAccountRefundLogVO> queryRefundDetail(Integer brandId, String paymentId) {
        Map<String, String> subAccountNames = subAccountDao.selectByAccountIdAndState(brandId, null, null, null)
                .stream().collect(Collectors.toMap(SubAccount::getMemberId, SubAccount::getNickName, (v1, v2) -> v2));
        List<SubAccountRefundLogVO> subAccountRefunds = subAccountLogDao.queryRefundDetail(paymentId);
        subAccountRefunds.forEach(subAccountUserRefund -> subAccountUserRefund.setNickName(subAccountNames.get(subAccountUserRefund.getUserNO())));
        return subAccountRefunds;
    }

    @Override
    public PageResult<RideFeeLog> queryRideFeeLogPage(Integer page, Integer size, Integer brandId, Integer accountId, Date startTime, Date endTime, Integer type) {
        //查询订单收费记录
        PageInfo<RideFeeLog> pageInfo = PageHelper.startPage(page, size).doSelectPageInfo(() -> rideFeeLogDao.queryRideFeeLogPage(brandId, accountId, startTime, endTime, type));
        return new PageResult<>(page, size, pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getList());
    }

    @Override
    public PageResult<RideFeeLog> queryRideFeeLogPageStatistics(Integer page, Integer size, Integer brandId, List<Integer> accountIdList, Date startTime, Date endTime, Integer type) {
        //查询订单收费记录
        PageInfo<RideFeeLog> pageInfo = PageHelper.startPage(page, size).doSelectPageInfo(() -> rideFeeLogDao.queryRideFeeLogPageByAccountIdList(brandId, accountIdList, startTime, endTime, type));
        Map<Integer, String> areaNameMap = getAreaNameMap(brandId);
        for (RideFeeLog rideFeeLog : pageInfo.getList()) {
            rideFeeLog.setAreaName(areaNameMap.get(rideFeeLog.getAccountId()));
        }
        return new PageResult<>(page, size, pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getList());
    }

    @Override
    public RideFeeLogStatisticsDTO selectRideFeeLogStatistics(Integer brandId, List<Integer> accountIdList, Date startTime, Date endTime, Integer type) {
        return rideFeeLogDao.selectRideFeeLogStatistics(brandId, accountIdList, startTime, endTime, type);
    }


    @Override
    public String downloadRideFeeLog(RideFeeLogDownloadDTO downloadDTO) {
        File tempFile = csvExportUtils.getTempFile();
        ExportHandler exportHandler = baseEntity -> {
            RideFeeLogDownloadDTO dto = com.tbit.uqbike.webmanager.util.BeanUtils.copyProperties(downloadDTO, RideFeeLogDownloadDTO.class);
            dto.setStartTime(baseEntity.getStartTime());
            dto.setEndTime(baseEntity.getEndTime());
            List<Integer> accountIdList = new ArrayList<>();
            if (!StringUtils.isEmpty(downloadDTO.getAccountIds())) {
                String[] accountArr = downloadDTO.getAccountIds().split(",");
                for (String accountId : accountArr) {
                    accountIdList.add(Integer.valueOf(accountId));
                }
            }
            List<RideFeeLog> list = rideFeeLogDao.queryRideFeeLogPageByAccountIdList(dto.getBrandId(), accountIdList,
                    dto.getStartTime(), dto.getEndTime(), dto.getType());
            Map<Integer, String> areaNameMap = getAreaNameMap(dto.getBrandId());
            for (RideFeeLog rideFeeLog : list) {
                rideFeeLog.setAreaName(areaNameMap.get(rideFeeLog.getAccountId()));
            }
            return list;
        };
        File file = csvExportUtils.export(exportHandler, RideFeeLog.class, downloadDTO.getStartTime(),
                downloadDTO.getEndTime(), tempFile, downloadDTO.getFileName());
        String uploadFileName = UUID.randomUUID().toString().replaceAll("-", "");
        return csvExportUtils.uploadZip(tempFile, uploadFileName, file);
    }

    @Override
    public String getRideFeeLogLastTime(Integer brandId, List<Integer> accountIdList, Integer type) {
        List<RideFeeLog> rideFeeLogs = rideFeeLogDao.selectLastRecord(brandId, accountIdList, type);
        if (!CollectionUtil.isEmpty(rideFeeLogs)) {
            return DateUtil.format(rideFeeLogs.get(0).getAddTime(), "yyyy-MM-dd HH:mm:ss");
        }
        return null;
    }

    @Override
    public PageResult<SubAccountWithdrawalLogVO> queryWithdrawalLog(Integer page, Integer size, Integer accountId, Date startTime, Date endTime, String accountUserPhone, Integer subAccountId, Integer schedule, Integer type) {
        PageInfo<SubAccountWithdrawalLogVO> pageInfo = PageHelper.startPage(page, size).doSelectPageInfo(() -> subAccountLogDao.queryWithdrawalLog(accountId, startTime, endTime, accountUserPhone, subAccountId, schedule, type));
        List<SubAccountWithdrawalLogVO> list = pageInfo.getList();
        List<SubAccount> subAccountList = subAccountDao.selectAll();
        Map<Integer, String> nickNameMap = new HashMap<>();
        for (SubAccount subAccount : subAccountList) {
            nickNameMap.put(subAccount.getSubAccountId(), subAccount.getNickName());
        }
        for (SubAccountWithdrawalLogVO subAccountWithdrawalLogVO : list) {
            subAccountWithdrawalLogVO.setNickName(nickNameMap.get(subAccountWithdrawalLogVO.getSubAccountId()));
        }
        return new PageResult<>(page, size, pageInfo.getTotal(), pageInfo.getSize(), list);
    }

    @Override
    public RideFeeLogTotalVO queryRideFeeLogTotal(Integer brandId, Integer accountId, Date startTime, Date endTime, Integer type) {
        RideFeeLogTotalVO rideFeeLogTotalVO = rideFeeLogDao.queryRideFeeLogTotal(brandId, accountId, startTime, endTime, type);
        if (rideFeeLogTotalVO == null) {
            rideFeeLogTotalVO = new RideFeeLogTotalVO(0, 0, 0, 0, 0, 0);
        }
        return rideFeeLogTotalVO;
    }

    @Override
    public List<SubAccountLogVO> exportSubAccountLog(LoginInfo login, Date startTime, Date endTime, Integer accountId, Integer adAccountId, String userNO, String buyOrderNO,String confirmId,String type) {
        Map<String, String> nickNameMap = getNickNameMap();
        Map<Integer, String> areaNameMap = getAreaNameMap(accountId);
        String checkUserNo = check(login, userNO);
        PageInfo<SubAccountLogVO> pageInfo = PageHelper.startPage(1, 60000).doSelectPageInfo(() -> adaPayCapitalDao.querySubAccountLogPage(startTime, endTime, accountId, adAccountId, checkUserNo, buyOrderNO,confirmId,type));
        List<SubAccountLogVO> subAccountLogVOS = pageInfo.getList();
        for (SubAccountLogVO subAccountLogVO : subAccountLogVOS) {
            //单独设置账号和区域名称
            String nickName = nickNameMap.get(subAccountLogVO.getUserNO());
            subAccountLogVO.setNickName(nickName);
            subAccountLogVO.setAreaName(areaNameMap.get(subAccountLogVO.getAccountId()));
            //单位转换
            subAccountLogVO.unitConversion();
        }
        return subAccountLogVOS;
    }

    @Override
    public List<SubAccountLogOverviewVO> exportSubAccountLogOverviewPageByDay(LoginInfo login, Date startTime, Date endTime, Integer accountId, Integer adAccountId, String userNO) {
        String checkUserNo = check(login, userNO);
//        List<SubAccountLogOverviewVO> logOverviewVOS = ledgerDayStatDao.querySubAccountLogOverviewPageOnceByDay(startTime, endTime, accountId, adAccountId, checkUserNo);
        List<SubAccountLogOverviewVO> logOverviewVOS = adaPayCapitalDao.querySubAccountLogOverviewPageOnceByDay(startTime, endTime, accountId, adAccountId, checkUserNo);
        Map<String, String> nickNameMap = getNickNameMap();
        for (SubAccountLogOverviewVO logOverviewVO : logOverviewVOS) {
            logOverviewVO.setNickName(nickNameMap.get(logOverviewVO.getUserNO()));
            //单位转换
            logOverviewVO.unitConversion();
        }
        return logOverviewVOS;
    }

    @Override
    public List<SubAccountUserRefundVO> exportSubAccountUserRefund(LoginInfo login, Date startTime, Date endTime, Integer accountId, Integer adAccountId, String userNO, String buyOrderNO,String confirmId,String type) {
        String checkUserNo = check(login, userNO);
        //查询退款明细
        Map<String, String> nickNameMap = getNickNameMap();
        Map<Integer, String> areaNameMap = getAreaNameMap(accountId);
        List<SubAccountUserRefundVO> list = adaPayCapitalDao.querySubAccountUserRefund(startTime, endTime, accountId, adAccountId, checkUserNo, buyOrderNO, confirmId,type);
        for (SubAccountUserRefundVO subAccountUserRefundVO : list) {
            //账号名称和区域赋值
            subAccountUserRefundVO.setAreaName(areaNameMap.get(subAccountUserRefundVO.getAccountId()));
            subAccountUserRefundVO.setNickName(nickNameMap.get(subAccountUserRefundVO.getUserNO()));
            //单位转换
            subAccountUserRefundVO.unitConversion();
        }
        return list;
    }

    @Override
    public List<SubAccountLogOverViewExportVO> exportSubAccountLogOverviewPage(LoginInfo login, Date startTime, Date endTime, Integer accountId, Integer adAccountId, String userNO) {
        List<SubAccountLogOverViewExportVO> exportVOList = new ArrayList<>();
        String checkUserNo = check(login, userNO);
        List<SubAccountLogOverviewVO> list = adaPayCapitalDao.querySubAccountLogOverviewPageOnce(startTime, endTime, accountId, adAccountId, checkUserNo);
//        List<SubAccountLogOverviewVO> list = ledgerDayStatDao.querySubAccountLogOverviewPage(startTime, endTime, accountId, adAccountId, checkUserNo);
        Map<String, String> nickNameMap = getNickNameMap();
        for (SubAccountLogOverviewVO logOverviewVO : list) {
            logOverviewVO.setNickName(nickNameMap.get(logOverviewVO.getUserNO()));
            //单位转换
            logOverviewVO.unitConversion();
            SubAccountLogOverViewExportVO exportVO = new SubAccountLogOverViewExportVO();
            //属性拷贝
            BeanUtils.copyProperties(logOverviewVO, exportVO);
            exportVOList.add(exportVO);
        }
        return exportVOList;
    }

    @Override
    public List<RideFeeLog> exportRideFeeLogPage(Integer brandId, Integer accountId, Date startTime, Date endTime, Integer type) {
        Map<Integer, String> areaNameMap = getAreaNameMap(brandId);
        //查询订单收费记录
        List<RideFeeLog> rideFeeLogs = rideFeeLogDao.queryRideFeeLogPage(brandId, accountId, startTime, endTime, type);
        for (RideFeeLog rideFeeLog : rideFeeLogs) {
            rideFeeLog.setAreaName(areaNameMap.get(rideFeeLog.getAccountId()));
            rideFeeLog.unitConversion();
        }
        return rideFeeLogs;
    }

    /**
     * 获取登录账户绑定的分账账户
     *
     * @param loginInfo
     * @return
     */
    public String check(LoginInfo loginInfo, String userNO) {
        if (UserConstant.USER_FRANCHISEE.equals(loginInfo.getType()) || UserConstant.USER_AGENT.equals(loginInfo.getType())) {
            //区域运营商或加盟商，只能查看绑定的分账账户信息
            String memberId = subAccountDao.selectBandMemberId(loginInfo.getAccountUserId());
            if (StringUtils.isEmpty(memberId)) {
                throw new BaseException("该账号尚未绑定分账账号");
            }
            return memberId;
        }
        return userNO;
    }

    /**
     * 获取用户编号和昵称对应map
     *
     * @return
     */
    public Map<String, String> getNickNameMap() {
        Map<String, String> nickNameMap = new HashMap<>();
        List<SubAccount> subAccountList = subAccountDao.selectAll();
        for (SubAccount subAccount : subAccountList) {
            nickNameMap.put(subAccount.getMemberId(), subAccount.getNickName());
        }
        //默认商户账户编号为0
        nickNameMap.put("0", "商户账号");
        return nickNameMap;
    }

    /**
     * 获取品牌下运营区域id对应的区域名map
     *
     * @param accountId 品牌id
     * @return
     */
    @Override
    public Map<Integer, String> getAreaNameMap(Integer accountId) {
        Map<Integer, String> areaNameMap = new HashMap<>();
        List<AreaVO> areaVO = accountDao.getAreaByBrandId(accountId);
        for (AreaVO vo : areaVO) {
            areaNameMap.put(vo.getAccountId(), vo.getName());
        }
        return areaNameMap;
    }

    @Override
    public int selectRideFeeLogCount(Integer brandId, Integer accountId, Date startTime, Date endTime, Integer type) {
        return rideFeeLogDao.queryRideFeeLogCount(brandId, accountId, startTime, endTime, type);
    }

    @Override
    public String downloadSubAccountLog(LoginInfo login, Date startTime, Date endTime, Integer accountId, Integer adAccountId, String userNO, String buyOrderNO,String confirmId,String type) {
        File tempFile = csvExportUtils.getTempFile();
        try {
            String checkUserNo = check(login, userNO);
            Map<String, String> nickNameMap = getNickNameMap();
            Map<Integer, String> areaNameMap = getAreaNameMap(accountId);
            IntSupplier countFn = () -> (int) PageHelper.startPage(1, 1).doSelectPageInfo(() -> adaPayCapitalDao.querySubAccountLogPage(startTime, endTime, accountId, adAccountId, checkUserNo, buyOrderNO,confirmId,type)).getTotal();
            ExportHandler exportHandler = baseEntity -> {
                List<SubAccountLogVO> subAccountLogVOS = adaPayCapitalDao.querySubAccountLogPage(baseEntity.getStartTime(), baseEntity.getEndTime(), accountId, adAccountId, checkUserNo, buyOrderNO,confirmId,type);
                System.out.println("数据长度:"+subAccountLogVOS.size());
                for (SubAccountLogVO subAccountLogVO : subAccountLogVOS) {
                    //单独设置账号和区域名称
                    String nickName = nickNameMap.get(subAccountLogVO.getUserNO());
                    subAccountLogVO.setNickName(nickName);
                    subAccountLogVO.setAreaName(areaNameMap.get(subAccountLogVO.getAccountId()));
                    //单位转换
                    subAccountLogVO.unitConversion();
                }
                return subAccountLogVOS;
            };
            File file = csvExportUtils.exportBigCsvUseDynamicDate(exportHandler, SubAccountLogVO.class, countFn, startTime, endTime, tempFile, "分账明细");
            return csvExportUtils.uploadZip(tempFile, UUID.randomUUID().toString().replace("-", ""), file);
        } finally {
            FileUtil.del(tempFile);
        }
    }


    @Override
    public String downloadSubAccountUserRefund(LoginInfo login, Date startTime, Date endTime, Integer accountId, Integer adAccountId, String userNO, String buyOrderNO,String confirmId,String type) {
        File tempFile = csvExportUtils.getTempFile();
        try {
            String checkUserNo = check(login, userNO);
            Map<String, String> nickNameMap = getNickNameMap();
            Map<Integer, String> areaNameMap = getAreaNameMap(accountId);
            IntSupplier countFn = () -> (int) PageHelper.startPage(1, 1).doSelectPageInfo(() -> adaPayCapitalDao.querySubAccountUserRefund(startTime, endTime, accountId, adAccountId, checkUserNo, buyOrderNO, confirmId,type)).getTotal();
            ExportHandler exportHandler = baseEntity -> {
                List<SubAccountUserRefundVO> subAccountLogVOS = adaPayCapitalDao.querySubAccountUserRefund(baseEntity.getStartTime(), baseEntity.getEndTime(), accountId, adAccountId, checkUserNo, buyOrderNO, confirmId,type);
                System.out.println("数据长度:"+subAccountLogVOS.size());
                for (SubAccountUserRefundVO subAccountUserRefundVO : subAccountLogVOS) {
                    //单独设置账号和区域名称
                    String nickName = nickNameMap.get(subAccountUserRefundVO.getUserNO());
                    subAccountUserRefundVO.setNickName(nickName);
                    subAccountUserRefundVO.setAreaName(areaNameMap.get(subAccountUserRefundVO.getAccountId()));
                    //单位转换
                    subAccountUserRefundVO.unitConversion();
                }
                return subAccountLogVOS;
            };
            File file = csvExportUtils.exportBigCsvUseDynamicDate(exportHandler, SubAccountUserRefundVO.class, countFn, startTime, endTime, tempFile, "分账详情-退款明细");
            return csvExportUtils.uploadZip(tempFile, UUID.randomUUID().toString().replace("-", ""), file);
        } finally {
            FileUtil.del(tempFile);
        }
    }




    @Override
    public  List<Map<String, Object>> queryRideMerchantPlatformRevenue(Integer brandId, List<Integer> accountId, Date startTime, Date endTime, Integer type) {
//        endTime = DateUtil.beginOfDay(endTime);
        List<Map<String, Object>> maps = rechargeDao.queryRideMerchantPlatformRevenue(brandId, accountId, startTime, endTime, type);
        return maps;
    }

    @Override
    public  List<Map<String, Object>> queryRideHSBCOperationalRevenue(Integer brandId, List<Integer> accountId, Date startTime, Date endTime, Integer type) {
//        endTime = DateUtil.beginOfDay(endTime);
        List<Map<String, Object>> maps = rechargeDao.queryRideHSBCOperationalRevenue(brandId, accountId, startTime, endTime, type);
        return maps;
    }


    @Override
    public   List<Map<String, Object>> queryRideHuifuRefund(Integer brandId, List<Integer> accountId, Date startTime, Date endTime, Integer type) {
//        endTime = DateUtil.beginOfDay(endTime);
        List<Map<String, Object>> maps = adaPayCapitalDao.queryRideHuifuRefund(brandId, accountId, startTime, endTime, type);
        return maps;
    }

    @Override
    public  PageResult<LedgerManagementVO> queryLedgerManagement( LoginInfo login,Integer page, Integer size,Integer brandId, List<Integer> accountId, Date startTime, Date endTime, Integer type,String userNO) {
        //排除品牌下数据到 位置区域
        if (accountId != null && accountId.contains(-1)){
            accountId.add(brandId);
        }
        String check = check(login, userNO);
        List<SubAccount> subAccounts = subAccountDao.selectByAccountIdAndState(brandId, 1, null, null);
        //账户名称
        Map<String, String> collect = subAccounts.stream().collect(Collectors.toMap(SubAccount::getMemberId, SubAccount::getNickName));
        //查询退款明细
        Map<Integer, String> areaNameMap = getAreaNameMap(brandId);
        PageInfo<LedgerManagementVO> pageInfo = PageHelper.startPage(page, size).doSelectPageInfo(() -> ledgerManagementDao.queryLedgerManagement(brandId, accountId, startTime, endTime, type,check));
        pageInfo.getList().stream().forEach((p) -> {
            p.setAreaName(areaNameMap.get(p.getAccountId()));
            if (p.getAccountId().equals(-1)) {
                p.setAreaName("未知区域");
            }
            p.setUserName(collect.get(p.getUserNO()));
            p.setAmountReceived(p.getMoney() + p.getRefundFee() - p.getRefundMoney() - p.getFee());
        });
        return new PageResult<>(page, size, pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getList());
    }


    @Override
    public  PageResult<LedgerManagementVO> queryLedgerManagementAll( LoginInfo login,Integer page, Integer size,Integer brandId, List<Integer> accountId, Date startTime, Date endTime, Integer type,String userNO) {
        //排除品牌下数据到 位置区域
        if (accountId != null && accountId.contains(-1)){
            accountId.add(brandId);
        }
        String check = check(login, userNO);
        List<SubAccount> subAccounts = subAccountDao.selectByAccountIdAndState(brandId, 1, null, null);
        //账户名称
        Map<String, String> collect = subAccounts.stream().collect(Collectors.toMap(SubAccount::getMemberId, SubAccount::getNickName));
        //查询退款明细
        Map<Integer, String> areaNameMap = getAreaNameMap(brandId);
        PageInfo<LedgerManagementVO> pageInfo = PageHelper.startPage(page, size).doSelectPageInfo(() -> ledgerManagementDao.queryLedgerManagementAll(brandId, accountId, startTime, endTime, type,check));
        pageInfo.getList().stream().forEach((p) -> {
            p.setAreaName(areaNameMap.get(p.getAccountId()));
            if (p.getAccountId().equals(-1)){
                p.setAreaName("未知区域");
            }
            p.setUserName(collect.get(p.getUserNO()));
            p.setAmountReceived(p.getMoney() + p.getRefundFee()- p.getRefundMoney()- p.getFee());
        });
        return new PageResult<>(page, size, pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getList());
    }




    @Override
    public String downloadLedgerManagement(  String token,Date startTime, Date endTime, Integer accountId, List<Integer> adAccountId, String userNO, Integer type) {
        //排除品牌下数据到 位置区域
        if (adAccountId != null && adAccountId.contains(-1)){
            adAccountId.add(accountId);
        }
        LoginInfo loginInfo = tokenService.getLoginInfo(token);
        String check = check(loginInfo, userNO);
        File tempFile = csvExportUtils.getTempFile();
        try {
            Map<String, String> nickNameMap = getNickNameMap();
            Map<Integer, String> areaNameMap = getAreaNameMap(accountId);
            //账户名称
            List<SubAccount> subAccounts = subAccountDao.selectByAccountIdAndState(accountId, 1, null, null);
            Map<String, String> collect = subAccounts.stream().collect(Collectors.toMap(SubAccount::getMemberId, SubAccount::getNickName));
            IntSupplier countFn = () -> (int) PageHelper.startPage(1, 1).doSelectPageInfo(() -> ledgerManagementDao.queryLedgerManagement(accountId, adAccountId, startTime, endTime, type,check)).getTotal();
            ExportHandler exportHandler = baseEntity -> {
                List<LedgerManagementVO> ledgerManagementVOS = ledgerManagementDao.queryLedgerManagement(accountId, adAccountId, startTime, endTime, type,check);
                System.out.println("数据长度:"+ledgerManagementVOS.size());
                for (LedgerManagementVO ledgerManagementVO : ledgerManagementVOS) {
                    //单独设置账号和区域名称
                    String nickName = nickNameMap.get(ledgerManagementVO.getUserNO());
                    ledgerManagementVO.setAreaName(nickName);
                    ledgerManagementVO.setAreaName(areaNameMap.get(ledgerManagementVO.getAccountId()));
                    ledgerManagementVO.setUserName(collect.get(ledgerManagementVO.getUserNO()));
                    ledgerManagementVO.setAmountReceived(ledgerManagementVO.getMoney() + ledgerManagementVO.getRefundFee()- ledgerManagementVO.getRefundMoney()- ledgerManagementVO.getFee());
                    //单位转换
                    ledgerManagementVO.unitConversion();
                }
                return ledgerManagementVOS;
            };
            File file = csvExportUtils.exportBigCsvUseDynamicDate(exportHandler, LedgerManagementVO.class, countFn, startTime, endTime, tempFile, "单日分账");
            return csvExportUtils.uploadZip(tempFile, UUID.randomUUID().toString().replace("-", ""), file);
        } finally {
            FileUtil.del(tempFile);
        }
    }

    @Override
    public String downloadLedgerManagementAll(  String token,Date startTime, Date endTime, Integer accountId, List<Integer> adAccountId, String userNO, Integer type) {
        //排除品牌下数据到 位置区域
        if (adAccountId != null && adAccountId.contains(-1)){
            adAccountId.add(accountId);
        }
        LoginInfo loginInfo = tokenService.getLoginInfo(token);
        String check = check(loginInfo, userNO);
        File tempFile = csvExportUtils.getTempFile();
        try {
            Map<String, String> nickNameMap = getNickNameMap();
            Map<Integer, String> areaNameMap = getAreaNameMap(accountId);
            List<SubAccount> subAccounts = subAccountDao.selectByAccountIdAndState(accountId, 1, null, null);
            Map<String, String> collect = subAccounts.stream().collect(Collectors.toMap(SubAccount::getMemberId, SubAccount::getNickName));
            IntSupplier countFn = () -> (int) PageHelper.startPage(1, 1).doSelectPageInfo(() -> ledgerManagementDao.queryLedgerManagementAll(accountId, adAccountId, startTime, endTime, type,check)).getTotal();
            ExportHandler exportHandler = baseEntity -> {
                List<LedgerManagementVO> ledgerManagementVOS = ledgerManagementDao.queryLedgerManagementAll(accountId, adAccountId, startTime, endTime, type, check);
                System.out.println("数据长度:"+ledgerManagementVOS.size());
                for (LedgerManagementVO ledgerManagementVO : ledgerManagementVOS) {
                    //单独设置账号和区域名称
                    String nickName = nickNameMap.get(ledgerManagementVO.getUserNO());
                    ledgerManagementVO.setAreaName(nickName);
                    ledgerManagementVO.setAreaName(areaNameMap.get(ledgerManagementVO.getAccountId()));
                    if (ledgerManagementVO.getAccountId().equals(-1)){
                        ledgerManagementVO.setAreaName("未知区域");
                    }
                    ledgerManagementVO.setUserName(collect.get(ledgerManagementVO.getUserNO()));
                    ledgerManagementVO.setAmountReceived(ledgerManagementVO.getMoney() + ledgerManagementVO.getRefundFee()- ledgerManagementVO.getRefundMoney()- ledgerManagementVO.getFee());
                    //单位转换
                    ledgerManagementVO.unitConversion();
                }
                return ledgerManagementVOS;
            };
            File file = csvExportUtils.exportBigCsvUseDynamicDate(exportHandler, LedgerManagementVO.class, countFn, startTime, endTime, tempFile, "总览分账");
            return csvExportUtils.uploadZip(tempFile, UUID.randomUUID().toString().replace("-", ""), file);
        } finally {
            FileUtil.del(tempFile);
        }
    }

    @Override
    public PageResult<RefundAdapayRecordVO> queryRefundAdapayRecord(LoginInfo login, Integer page, Integer size, Date startTime, Date endTime, Integer brandId, Integer areaId, String userNO, String rechargeNO, String adapayNO) {
        Assert.notNulls("参数有误", page, size, startTime, endTime,brandId);
        String checkUserNo = check(login, userNO);
        //查询退款明细
        Map<String, String> nickNameMap = getNickNameMap();
        Map<Integer, String> areaNameMap = getAreaNameMap(brandId);
        PageInfo<RefundAdapayRecordVO> pageInfo = PageHelper.startPage(page, size).doSelectPageInfo(() -> subAccountLogDao.queryRefundAdapayRecord(startTime, endTime, brandId, areaId, checkUserNo, rechargeNO, adapayNO));

        List<RefundAdapayRecordVO> refundAdapayRecordVOList = pageInfo.getList();
        for (RefundAdapayRecordVO refundAdapayRecordVO : refundAdapayRecordVOList) {
            //单独设置账号和区域名称
            String nickName = nickNameMap.get(refundAdapayRecordVO.getUserNO());
            refundAdapayRecordVO.setNickName(nickName);
            refundAdapayRecordVO.setAreaName(areaNameMap.get(refundAdapayRecordVO.getAreaId()));
            //单位转换
            refundAdapayRecordVO.unitConversion();
        }
        return new PageResult<>(page, size, pageInfo.getTotal(), pageInfo.getSize(), refundAdapayRecordVOList);
    }

    @Override
    public String downloadRefundAdapayRecord(LoginInfo login, Date startTime, Date endTime, Integer brandId, Integer areaId, String userNO, String rechargeNO, String adapayNO) {
        File tempFile = csvExportUtils.getTempFile();
        try {
            String checkUserNo = check(login, userNO);
            Map<String, String> nickNameMap = getNickNameMap();
            Map<Integer, String> areaNameMap = getAreaNameMap(brandId);
            IntSupplier countFn = () -> (int) PageHelper.startPage(1, 1).doSelectPageInfo(() -> subAccountLogDao.queryRefundAdapayRecord(startTime, endTime, brandId, areaId, checkUserNo, rechargeNO, adapayNO)).getTotal();
            ExportHandler exportHandler = baseEntity -> {
                List<RefundAdapayRecordVO> refundAdapayRecordVOS = subAccountLogDao.queryRefundAdapayRecord(startTime, endTime, brandId, areaId, checkUserNo, rechargeNO, adapayNO);
                System.out.println("数据长度:" + refundAdapayRecordVOS.size());
                for (RefundAdapayRecordVO refundAdapayRecord : refundAdapayRecordVOS) {
                    //单独设置账号和区域名称
                    String nickName = nickNameMap.get(refundAdapayRecord.getUserNO());
                    refundAdapayRecord.setNickName(nickName);
                    refundAdapayRecord.setAreaName(areaNameMap.get(refundAdapayRecord.getAreaId()));
                    //单位转换
                    refundAdapayRecord.unitConversion();
                }
                return refundAdapayRecordVOS;
            };
            File file = csvExportUtils.exportBigCsvUseDynamicDate(exportHandler, RefundAdapayRecordVO.class, countFn, startTime, endTime, tempFile, "分账详情-退款明细");
            return csvExportUtils.uploadZip(tempFile, UUID.randomUUID().toString().replace("-", ""), file);
        } finally {
            FileUtil.del(tempFile);
        }
    }




/*    @Scheduled(cron = "0 0 8 * * ?")
    public void task1() {
        Boolean flag = dateMap.get("flag");

        String formattedDate = null;
        if(null != flag ){
            Integer querydata = ledgerManagementDao.querydata();
            if ( !querydata.equals(0)){
                // 获取当前时间戳
                long currentTimeMillis = System.currentTimeMillis();

                // 减去一天的毫秒数
                long previousDayMillis = currentTimeMillis - 24 * 60 * 60 * 1000;

                // 获取前一天日期
                Date previousDate = new Date(previousDayMillis);

                // 创建一个日期格式化对象
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                // 格式化日期并输出
               formattedDate = sdf.format(previousDate);
                LogUtil.info("分账管理定时任务日期" + formattedDate);
            }

        }else {
            dateMap.put("flag",true);
        }
        List<LedgerManagementVO> ledgerManagementList = adaPayCapitalDao.getLedgerManagementList(formattedDate);
        if (ledgerManagementList.size() > 0){
            ledgerManagementDao.insert(ledgerManagementList);
        }


    }*/

}
